<template>
  <div class='container'>
    <el-card>
      <template #header>
        <span>试题录入</span>
      </template>

      <!-- 表单部分 -->
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="120px">

        <!-- 学科 -->
        <el-form-item label="学科：" prop="subjectID">
          <el-select style="width:400px" v-model="ruleForm.subjectID" @change="subChange">
            <el-option
              v-for="item in subjectList"
              :key="item.value"
              :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>

        <!-- 目录 -->
        <el-form-item label="目录：" prop="catalogID">
          <el-select style="width:400px" v-model.trim="ruleForm.catalogID">
            <el-option
              v-for="item in directorysList"
              :key="item.id"
              :label="item.directoryName"
              :value="item.id" />
          </el-select>
        </el-form-item>

        <!-- 企业 -->
        <el-form-item label="企业：" prop="enterpriseID">
          <el-select style="width:400px" v-model="ruleForm.enterpriseID">
            <el-option
              v-for="item in companysList"
              :key="item.company"
              :label="item.company"
              :value="item.id" />
          </el-select>
        </el-form-item>

        <!-- 城市  城市、地区联动 -->
        <el-form-item label="城市：" prop="city">
          <el-select style="width:198px" v-model="ruleForm.province">
            <el-option
              v-for="item in citySelect.province"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
          <el-select style="width: 198px; margin-left: 4px;" v-model="ruleForm.city">
            <el-option
              v-for="item in citySelect.cityDate"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 方向 -->
        <el-form-item label="方向：" prop="direction">
          <el-select style="width:400px" v-model="ruleForm.direction">
            <el-option
              v-for="item in directionList"
              :value="item"
              :key="item"
              :label="item"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 题型 -->
        <el-form-item label="题型：" prop="questionType">
          <el-radio-group v-model.trim="ruleForm.questionType">
            <!-- v-model="radio" -->
            <el-radio
              v-for="item in questionTypeList"
              :key="item.value"
              :label="item.value+''"
              :value="item.value"
            >{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 难度 -->
        <el-form-item label="难度：">
          <el-radio-group v-model.trim="ruleForm.difficulty">
            <el-radio
              v-for="item in difficultyList"
              :key="item.value"
              :label="item.value+''"
              :value="item.value"
            >{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 题干   -->
        <el-form-item label="题干：" prop="question">
          <!-- 富文本编辑器 -->
          <quill-editor :options="editorOption" v-model="ruleForm.question"></quill-editor>
        </el-form-item>

        <!-- 选项    单选-->
        <el-form-item label="选项：" v-if="ruleForm.questionType==='1'">
          <template>
            <el-radio-group v-model="radioChecked" @input="checkedChange">
              <div class="option_item" style="padding-bottom:22px" v-for="item in ruleForm.options" :key="item.code">
                  <el-radio :label="item.code">
                    <span>{{item.code}}：</span>
                  </el-radio>
                  <el-input style="width:240px" v-model="item.title"/>
                  <el-upload
                    class="avatar-uploader"
                    action="https://jsonplaceholder.typicode.com/posts/"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload">
                    <span>上传图片</span>
                    <i class="el-icon-circle-close"></i>
                  </el-upload>
              </div>
              <el-button type="danger" size="small" @click="addQuestion" disabled>+增加选项与答案</el-button>
            </el-radio-group>
          </template>
        </el-form-item>

        <!-- 选项   多选 -->
        <el-form-item label="选项：" v-else-if="ruleForm.questionType==='2'">
            <template>
                <el-checkbox-group v-model="checked" @change="checkedChange">
                  <div class="option_item" style="padding-bottom:22px" v-for="item in ruleForm.options" :key="item.code">
                    <el-checkbox :label="item.code">
                      <span>{{item.code}}：</span>
                    </el-checkbox>
                    <el-input style="width:240px" v-model="item.title"/>
                    <el-upload
                      class="avatar-uploader"
                      action="https://jsonplaceholder.typicode.com/posts/"
                      :show-file-list="false"
                      :on-success="handleAvatarSuccess"
                      :before-upload="beforeAvatarUpload">
                      <span>上传图片</span>
                      <i class="el-icon-circle-close"></i>
                    </el-upload>
                  </div>
                </el-checkbox-group>
              <el-button type="danger" size="small" @click="addQuestion">+增加选项与答案</el-button>
            </template>
        </el-form-item>

        <!-- 解析视频 -->
        <el-form-item label="解析视频：">
          <el-input style="width:400px" v-model="ruleForm.videoURL"/>
        </el-form-item>

        <!-- 答案解析 -->
        <el-form-item label="答案解析：" prop="answer">
          <quill-editor :options="editorOption" v-model="ruleForm.answer"></quill-editor>
        </el-form-item>

        <!-- 题目备注 -->
        <el-form-item label="题目备注：">
          <el-input type="textarea" :rows="4" style="width:400px" v-model="ruleForm.remarks"></el-input>
        </el-form-item>

        <!-- 试题标签 -->
        <el-form-item label="试题标签：">
          <el-select
          @change="selectTagsChange"
            v-model="selectTags"
            multiple
            filterable
            allow-create
            default-first-option
            style="width:400px"
            placeholder="请选择试题标签">
            <el-option
              v-for="item in tagsList"
              :key="item.id"
              :label="item.tagName"
              :value="item.tagName" />
          </el-select>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button v-if="articleId" type="success" @click="submitForm">确认修改</el-button>
          <el-button v-else type="primary" @click="submitForm">确认提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor as QuillEditor } from 'vue-quill-editor'

// 学科
import { simple as getSubjectListData } from '@/api/hmmm/subjects.js'

// 目录
import { list as getDirectorysListData } from '@/api/hmmm/directorys.js'

// 企业
import { list as getCompanysListData } from '@/api/hmmm/companys.js'

// 城市
import { provinces, citys } from '@/api/hmmm/citys.js'

// 难度，题型，方向
import { difficulty, questionType, direction } from '@/api/hmmm/constants.js'

// 标签
import { list as getTagsListData } from '@/api/hmmm/tags.js'

// 试题添加接口  修改接口
import { add, detail, update } from '@/api/hmmm/questions.js'

// 工具栏配置项
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'],
  [{ list: 'ordered' }, { list: 'bullet' }],
  ['blockquote'],
  ['code-block', 'image', 'link']
]
export default {
  data () {
    return {
      articleId: this.$route.query.id || '',
      radioChecked: '',
      checked: [],
      editorOption: {
        modules: {
          toolbar: toolbarOptions
        },
        placeholder: ''
      },
      subjectList: [],
      directorysList: [],
      tagsList: [],
      selectTags: '',
      companysList: [],
      citySelect: {
        province: [],
        cityDate: []
      },
      directionList: [],
      difficultyList: [],
      questionTypeList: [],
      ruleForm: {
        // 学科
        subjectID: '',
        // 目录
        catalogID: '',
        // 企业
        enterpriseID: '',
        // 城市
        province: '',
        // 地区
        city: '',
        // 方向
        direction: '',
        // 题型
        questionType: '1',
        // 难度
        difficulty: '1',
        // 题干
        question: '',
        // 选项
        options: [
          {
            // 是否正确答案
            isRight: false,
            // 代码
            code: 'A',
            // 标题
            title: '',
            // 图片
            img: ''
          },
          {
            isRight: false,
            code: 'B',
            title: '',
            img: ''
          },
          {
            isRight: false,
            code: 'C',
            title: '',
            img: ''
          },
          {
            isRight: false,
            code: 'D',
            title: '',
            img: ''
          }

        ],
        // 解析视频
        videoURL: '',
        // 答案解析
        answer: '',
        // 题目备注
        remarks: '',
        // 试题标签
        tags: ''

      },
      rules: {
        subjectID: [{ required: true, message: '请选择学科' }],
        catalogID: [{ required: true, message: '请选择目录' }],
        enterpriseID: [{ required: true, message: '请选择企业' }],
        city: [{ required: true, message: '请选择地区' }],
        direction: [{ required: true, message: '请选择方向' }],
        questionType: [{ required: true }],
        question: [{ required: true, message: '请输入题干' }],
        answer: [{ required: true, message: '请输入答案解析' }]
      }

    }
  },
  components: {
    QuillEditor
  },
  watch: {
    // 监听学科 获取目录列表 标签列表
    async 'ruleForm.subjectID' (val) {
      const res = await getDirectorysListData()
      // console.log(res.data.items)
      this.directorysList = res.data.items.filter(item => item.subjectID === val)
      // console.log(this.directorysList)
      const res1 = await getTagsListData()
      console.log(res1.data.items)
      this.tagsList = res1.data.items.filter(item => item.subjectID === val)
    },
    async 'ruleForm.province' (val) {
      // console.log(e)
      this.citySelect.cityDate = citys(val)
    }
  },
  methods: {
    // 处理单选多选选中的值
    checkedChange (val) {
      if (Array.isArray(val)) {
        this.ruleForm.options.forEach(ele => {
          ele.isRight = val.includes(ele.code)
        })
        return
      }
      this.ruleForm.options.forEach(ele => {
        ele.isRight = ele.code === val
      })
    },
    // 随机顺序生成ABCDE...字母的函数
    setDesc () {
      const letterArr = []
      // 字母A的code值是65，但因为已经到字母D了，所以直接从69E开始循环
      for (let i = 69; i < 91; i++) {
        letterArr[i] = String.fromCharCode(i)
      }
      console.log(letterArr)
      return letterArr
    },
    // 增加选项和答案按钮
    addQuestion () {
      // 调用随机顺序生成ABCDE...字母的函数，可以打印randomAbc 数组看下
      // 有69个元素是空的，所以直接进行了截取
      console.log(this.setDesc())
      const randomAbc = this.setDesc().splice(65)
      const res = [
        ...this.ruleForm.options,
        {
          code: `${randomAbc[this.ruleForm.options.length]}`,
          title: '',
          img: '',
          isRight: false
        }
      ]
      this.ruleForm.options = res
    },
    handleAvatarSuccess (response, file, fileList) {
      // 处理上传成功事件
    },
    beforeAvatarUpload (file) {
      // 验证和处理上传前的逻辑
    },

    // 获取学科列表
    async getSubjectList () {
      const res = await getSubjectListData()
      // console.log(res)
      this.subjectList = res.data
    },
    //
    subChange () {
      this.ruleForm.catalogID = ''
      this.ruleForm.tags = ''
      this.selectTags = ''
    },
    // 获取企业列表
    async getCompanysList () {
      const companyslist = await getCompanysListData()
      // console.log(companyslist.data.items)
      this.companysList = companyslist.data.items
    },

    // 获取省
    getCityData () {
      this.citySelect.province = provinces()
    },

    // 获取方向数据
    getDirectionData () {
      this.directionList = direction
    },

    // 获取难度数据
    getDifficultyData () {
      this.difficultyList = difficulty
    },

    // 获取题型数据
    getQuestionTypeData () {
      this.questionTypeList = questionType
    },
    // 处理标签
    selectTagsChange () {
      this.ruleForm.tags = this.selectTags.join(',')
    },

    // 修改  数据回显
    async getArtDitail (id) {
      console.log(id)
      const res = await detail({ id })
      console.log(res)
      this.selectTags = res.data.tags.split(',')
      this.ruleForm = res.data
      this.ruleForm.options.forEach(ele => {
        ele.isRight = ele.isRight === 1
        if (ele.isRight) {
          if (this.ruleForm.questionType === '1') this.radioChecked = ele.code
          if (this.ruleForm.questionType === '2') this.checked.push(ele.code)
        }
      })
    },
    // 表单校验
    submitForm () {
      this.$refs.ruleForm.validate(async (isOk) => {
        if (!isOk) return
        if (!this.articleId) {
          await add(this.ruleForm)
          this.$message.success('添加试题成功')
        } else {
          await update(this.ruleForm)
          this.$message.success('修改试题成功')
        }

        // 重置表单
        this.radioChecked = ''
        this.checked = []
        this.$refs.ruleForm.resetFields()
        this.ruleForm = {
        // 学科
          subjectID: '',
          // 目录
          catalogID: '',
          // 企业
          enterpriseID: '',
          // 城市
          province: '',
          // 地区
          city: '',
          // 方向
          direction: '',
          // 题型
          questionType: '1',
          // 难度
          difficulty: '1',
          // 题干
          question: '',
          // 选项
          options: [
            {
            // 是否正确答案
              isRight: false,
              // 代码
              code: 'A',
              // 标题
              title: '',
              // 图片
              img: ''
            },
            {
              isRight: false,
              code: 'B',
              title: '',
              img: ''
            },
            {
              isRight: false,
              code: 'C',
              title: '',
              img: ''
            },
            {
              isRight: false,
              code: 'D',
              title: '',
              img: ''
            }

          ],
          // 解析视频
          videoURL: '',
          // 答案解析
          answer: '',
          // 题目备注
          remarks: '',
          // 试题标签
          tags: ''

        }
        this.$router.push('/questions/list')
      })
    }
  },
  created () {
    if (this.$route.query.id) this.getArtDitail(this.$route.query.id)

    this.getSubjectList()

    this.getCompanysList()

    this.getCityData()

    this.getDirectionData()

    this.getDifficultyData()

    this.getQuestionTypeData()
  }

}
</script>

<style scoped lang='less'>
.container{
  padding: 20px;
  .el-card{
    .el-form{
      /deep/ .el-form-item {
        margin-bottom: 22px !important;
      }
      .quill-editor {
        height: 200px;
        margin-bottom: 60px !important;
      }
      // 单选
      .el-radio-group{
        .option_item{

          .el-radio{
            margin-right: 0;
          }
          //上传图片--------------------------
          .avatar-uploader {
            position: relative;
            display: inline-block !important;
            width: 100px;
            height: 60px;
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            margin-left: 4px;
            line-height: 60px;
            text-align: center;
            cursor: pointer;
            span{
              cursor: pointer;
              font-size: 14px;
            }
            .el-icon-circle-close{
              position: absolute;
              right: 0;
              top: 0;
              transform: translate(50%,-50%);
              background: #fff;
              font-size: 18px;
              color: #999;
            }
          }
          .avatar-uploader:hover {
            border-color: #409EFF;
          }
          // 上传图片-------------------------
        }
      }
      // 多选
      .el-checkbox-group{
        .option_item{

          .el-checkbox{
            margin-right: 0;
          }
          //上传图片--------------------------
          .avatar-uploader {
            position: relative;
            display: inline-block !important;
            width: 100px;
            height: 60px;
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            margin-left: 4px;
            line-height: 60px;
            text-align: center;
            cursor: pointer;
            span{
              cursor: pointer;
              font-size: 14px;
            }
            .el-icon-circle-close{
              position: absolute;
              right: 0;
              top: 0;
              transform: translate(50%,-50%);
              background: #fff;
              font-size: 18px;
              color: #999;
            }
          }
          .avatar-uploader:hover {
            border-color: #409EFF;
          }
          // 上传图片-------------------------
        }
      }
    }

  }
}
</style>
